package com.hongye.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.hongye.app.model.OrderInfoModel;
import com.hongye.app.model.PaymentModel;
import com.hongye.util.AlipayUtils;
import com.hongye.util.JsonUtils;
import com.hongye.util.PushUtils;
import com.hongye.util.Utils;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.mysql.jdbc.StringUtils;

/**
 * 支付宝相关处理
 * @author Administrator
 *
 */
public class AlipayController extends Controller{
	private static Logger log = Logger.getLogger(AlipayController.class);
	
	public AlipayController() {
		
	}
	
	/**
	 * APP支付添加签名
	 * @author lifuqiang
	 * 2016-12-2
	 */
	@Clear
	public void getAppAlipaySign(){
		Map<String, Object> rs = new HashMap<String, Object>();
		String orderids = this.getPara("orderid");
		Map<String, String> sParaTemp = new HashMap<String, String>();
		Map<String, Object> biz_content = new HashMap<String, Object>();
		sParaTemp.put("app_id", AlipayUtils.APPID);//支付宝分配给开发者的应用ID
		sParaTemp.put("charset", AlipayUtils.UTF_8);//参数编码字符集
		sParaTemp.put("format", "json");
		sParaTemp.put("method", "alipay.trade.app.pay");//接口名称
		sParaTemp.put("notify_url", AlipayUtils.NOTIFY_URL_APP);//服务器异步通知页面处理地址 	
		sParaTemp.put("timestamp", Utils.getDate());//发送请求的时间
		sParaTemp.put("version", "1.0");//调用的接口版本，固定为：1.0
		sParaTemp.put("sign_type", "RSA");//商户生成签名字符串所使用的签名算法类型
		boolean boo = orderids.contains(",");
		List<OrderInfoModel> orders =OrderInfoModel.getOrderByINOrderids(orderids);
		if (boo) {
			float summoney = (float) 0.0;
			for (OrderInfoModel item : orders) {
				summoney += item.getFloat("total_price");
			}
			OrderInfoModel orderinfo = new OrderInfoModel();
			orderinfo.set("type", 1).set("orderids", orderids).set("total_price", Utils.decimalFormat(summoney)).set("payment_channel", "1").set("order_sn", Utils.getOrderSN()).set("order_status", 0).save();
			biz_content.put("subject", "热播购平台批量付款");//商品的标题/交易标题/订单标题/订单关键字等
			biz_content.put("out_trade_no", orderinfo.get("order_sn"));//商户网站唯一订单号
			biz_content.put("total_amount",  Utils.decimalFormat(summoney));//订单总金额
		}else{
			biz_content.put("subject", "热播购平台付款");//商品的标题/交易标题/订单标题/订单关键字等
			biz_content.put("out_trade_no", orders.get(0).get("order_sn"));//商户网站唯一订单号
			biz_content.put("total_amount", orders.get(0).getFloat("total_price"));//订单总金额
		}
		biz_content.put("timeout_express", "30m");//该笔订单允许的最晚付款时间，逾期将关闭交易。
		biz_content.put("product_code", "QUICK_MSECURITY_PAY");	//销售产品码，商家和支付宝签约的产品码，为固定值
		sParaTemp.put("biz_content", JsonUtils.serialize(biz_content));		//业务请求参数的集合
		String sign = AlipayUtils.Signature(sParaTemp, AlipayUtils.PRIVATE_ALIPAY_KEY_PKCS8, AlipayUtils.UTF_8);
		sParaTemp.put("sign", sign);
		String result = AlipayUtils.createLinkString(AlipayUtils.ValueToEncode(sParaTemp));
		PaymentModel.dao.addPayment(orders, "alipay");
		if(log.isInfoEnabled()){log.info("data= " + result);}
		rs.put("data", result);
		this.renderJson(rs);
	}
	
	/**
	 * APP同步支付结果返回服务器,返回支付结果
	 * 不做支付校验，校验在异步通知接口做
	 * @author liushaomin
	 * 2016年12月5日
	 */
	@SuppressWarnings("unchecked")
	@Clear
	public void appSynchroResult(){
		Map<String, Object> rs = new HashMap<String, Object>();
		String data = this.getPara("data");
		rs.put("state", "cancel");
		if(!StringUtils.isNullOrEmpty(data)){
			Map<String, Object> mapdata = JsonUtils.deserialize(data);
			Map<String, Object> alipay_response = (Map<String, Object>) mapdata.get("alipay_trade_app_pay_response");
			String ordersn = alipay_response.get("out_trade_no").toString();
			OrderInfoModel order = OrderInfoModel.getOrderBySN(ordersn);
			if(order.getInt("order_status") == 2){
				rs.put("money", order.getFloat("total_price"));
				rs.put("state", "suc");
			}else{
				AlipayUtils.refund(ordersn, order.get("total_price"));//验证失败 执行退款
				rs.put("state", "fal");
			}
		}
		this.renderJson(rs);
	}
	
	/**
	 * APP alipay异步回调地址（App）notifyUrl
	 * 支付成功后 更新order 在更新payment
	 * 返回给支付宝 success
	 * @author lifuqiang
	 * 2016-12-2
	 */
	@Clear
	public void appNotify(){
		String total_amount = this.getPara("total_amount");//订单金额
		String buyer_id = this.getPara("buyer_id");//买家支付宝用户号
		String trade_no = this.getPara("trade_no");//支付宝交易号
		String notify_time = this.getPara("notify_time");//通知时间
		String subject = this.getPara("subject");//订单标题
		String sign_type = this.getPara("sign_type");//签名类型
		String charset = this.getPara("charset");//编码格式
		String notify_type = this.getPara("notify_type");//通知类型
		String ordersn = this.getPara("out_trade_no");//商户订单号
		String gmt_payment = this.getPara("gmt_payment");//交易付款时间
		String trade_status = this.getPara("trade_status");//交易状态
		String version = this.getPara("version");//接口版本
		String sign = this.getPara("sign");//sign
		String gmt_create = this.getPara("gmt_create");//交易创建时间
		String app_id = this.getPara("app_id");//支付宝分配给开发者的应用Id
		String seller_id = this.getPara("seller_id");//卖家支付宝用户号
		String notify_id = this.getPara("notify_id");//通知校验ID
		String buyer_logon_id = this.getPara("buyer_logon_id");//买家支付宝账号
		String seller_email = this.getPara("seller_email");//卖家支付宝账号
		String auth_app_id = this.getPara("auth_app_id");//
		String fund_bill_list = this.getPara("fund_bill_list");
		String invoice_amount = this.getPara("invoice_amount");
		String point_amount = this.getPara("point_amount");
		String buyer_pay_amount = this.getPara("buyer_pay_amount");
		String receipt_amount = this.getPara("receipt_amount");
		if(log.isInfoEnabled()){log.info("notifyUrl para:total_amount=" + total_amount+"&buyer_id=" + buyer_id+"&trade_no=" + trade_no
				+"&notify_time="+ notify_time+"&subject="+ subject+"&sign_type="+ sign_type +"&charset="+ charset +"&notify_type="+ notify_type
				+"&out_trade_no="+ ordersn+"&gmt_payment="+ gmt_payment+"&trade_status="+ trade_status+"&version="+ version
				+"&gmt_create="+ gmt_create+"&app_id="+ app_id+"&seller_id="+ seller_id+"&notify_id="+ notify_id+"&buyer_logon_id="+ buyer_logon_id
				+"&seller_email="+ seller_email +"&auth_app_id=" + auth_app_id + "&fund_bill_list=" + fund_bill_list + "&invoice_amount=" + invoice_amount
				+"&point_amount=" + point_amount +"&buyer_pay_amount=" + buyer_pay_amount + "&receipt_amount=" + receipt_amount);}
		if(log.isInfoEnabled()){log.info("notifyUrl sign=" + sign);}
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("total_amount", total_amount);
		sParaTemp.put("buyer_id", buyer_id);
		sParaTemp.put("trade_no", trade_no);
		sParaTemp.put("notify_time", notify_time);
		sParaTemp.put("subject", subject);
		sParaTemp.put("charset", charset);
		sParaTemp.put("notify_type", notify_type);
		sParaTemp.put("out_trade_no", ordersn);
		sParaTemp.put("gmt_payment", gmt_payment);
		sParaTemp.put("trade_status", trade_status);	
		sParaTemp.put("version", version);
		sParaTemp.put("gmt_create", gmt_create);
		sParaTemp.put("app_id", app_id);
		sParaTemp.put("seller_id", seller_id);
		sParaTemp.put("notify_id", notify_id);
		sParaTemp.put("buyer_logon_id", buyer_logon_id);
		sParaTemp.put("seller_email", seller_email);
		sParaTemp.put("fund_bill_list", fund_bill_list);
		sParaTemp.put("auth_app_id", auth_app_id);
		sParaTemp.put("sign", sign);
		sParaTemp.put("sign_type", sign_type);
		sParaTemp.put("invoice_amount", invoice_amount);
		sParaTemp.put("point_amount", point_amount);
		sParaTemp.put("buyer_pay_amount", buyer_pay_amount);
		sParaTemp.put("receipt_amount", receipt_amount);
		String result = "failure";
		if(AlipayUtils.signVerified(sParaTemp)){
			result = "success";
			if (subject.equals("热播购平台批量付款")) {//多个订单支付
				OrderInfoModel order = OrderInfoModel.getOrderBySN(ordersn);
				String orderids = order.getStr("orderids");
				List<PaymentModel> payments = PaymentModel.getListByOrderids_Channel(orderids,"alipay");;
				for (PaymentModel item : payments) {
					if(trade_status.equals("TRADE_SUCCESS")){
					    order.set("order_status", 2).update();
						OrderInfoModel orderitem = OrderInfoModel.getOrderBySN(item.getStr("ordersn"));
						if(orderitem.getInt("order_status") == 0){
							if(OrderInfoModel.UpdateStatusByOrdersn(item.getStr("ordersn"), "0", null)){//更新订单状态 
								item.set("payment_account", buyer_logon_id).set("successtime", notify_time).set("state", 2).update();
								PushUtils.MSG_Single(OrderInfoModel.getSellerByOrdersn(orderitem.getStr("order_sn")), "B01", "您有一个新订单，赶紧去发货吧！");//添加通知推送
							}
						}
					}else if(trade_status.equals("TRADE_CLOSED")){
						OrderInfoModel orderitem = OrderInfoModel.getOrderBySN(item.getStr("ordersn"));
						if(orderitem.getInt("order_status") == 2){
							if(OrderInfoModel.UpdateOrderStatus(orderitem, 9)){//更新订单状态 为 退款成功
								item.set("state", 3).update();
								order.set("order_status", 9).update();
							}
						}else{
							item.set("payment_account", buyer_logon_id).set("successtime", notify_time).set("state", 1).update();//未付款，交易超时关闭
						}
					}
				}
			}else{
				PaymentModel payment = PaymentModel.getPaymentByOrderSN_Channel_state(ordersn, "alipay", 0);
				OrderInfoModel order = OrderInfoModel.getOrderBySN(ordersn);
				if(trade_status.equals("TRADE_SUCCESS")){
					if(order.getInt("order_status") == 0){
						if(OrderInfoModel.UpdateStatusByOrdersn(ordersn, "0", null)){//更新订单状态 
							payment.set("payment_account", buyer_logon_id).set("successtime", notify_time).set("state", 2).update();
							PushUtils.MSG_Single(OrderInfoModel.getSellerByOrdersn(ordersn), "B01", "您有一个新订单，赶紧去发货吧！");//添加通知推送
						}
					}
				}else if(trade_status.equals("TRADE_CLOSED")){//未付款，交易超时关闭
					if(order.getInt("order_status") == 2){
						if(OrderInfoModel.UpdateOrderStatus(order, 9)){//更新订单状态 为 退款成功
							payment.set("state", 3).update();
						}
					}else{
						payment.set("payment_account", buyer_logon_id).set("successtime", notify_time).set("state", 1).update();
					}
				}
			}
		}
		if(log.isInfoEnabled()){log.info("notifyUrl result=" + result);}
		this.renderJson(result);
	}
	
	
	/**
	 * 批量付款到支付宝账号---------服务器异步通知
	 * @author liushaomin
	 * 2016年12月13日
	 */
	@Clear
	public void serNotify(){
//		String notify_time = this.getPara("notify_time");//通知时间
//		String notify_type = this.getPara("notify_type");//通知类型
//		String notify_id = this.getPara("notify_id");//通知校验ID
//		String sign_type = this.getPara("sign_type");//签名方式
//		String sign = this.getPara("sign");//签名
//		String batch_no = this.getPara("batch_no");//批次号
//		String pay_user_id = this.getPara("pay_user_id");//付款账号ID
//		String pay_user_name = this.getPara("pay_user_name");//付款账号姓名
//		String pay_account_no = this.getPara("pay_account_no");//付款账号
//		String success_details = this.getPara("success_details");//转账成功的详细信息
//		String fail_details = this.getPara("fail_details");//转账失败的详细信息
//		if(log.isInfoEnabled()){log.info("serNotify para:notify_time =" + notify_time + "&notify_type=" + notify_type + "&notify_id=" + notify_id +"&sign_type =" + sign_type
//				+"&batch_no ="+ batch_no +"&pay_user_id ="+ pay_user_id +"&pay_user_name ="+ pay_user_name +"&pay_account_no ="+ pay_account_no
//				+"&success_details="+ success_details +"&fail_details="+ fail_details);}
//		if(log.isInfoEnabled()){log.info("serNotify sign=" + sign);}
//		
		System.err.println("执行================serNotify");
		this.renderJsp("notify_url.jsp");
	}
	
	
	
}
